<template>
 <div>

   <com-test :value.sync="comValue" @changeValue="changeValue"></com-test>
   从子组件传回来的值：{{comValue}}

   <div style="width: 400px">

     <el-select
         v-model="value2"
         multiple
         collapse-tags
         style="margin-left: 20px;"
         placeholder="请选择"
        @change="changeMulSelect">
       <el-option
           v-for="item in options"
           :key="item.value"
           :label="item.label"
           :value="item.value">
       </el-option>
     </el-select>

     <el-button @click="compare">两个集合</el-button>
     <el-select v-model="value" placeholder="请选择">
       <el-option
           v-for="item in options"
           :key="item.value"
           :label="item.label"
           :value="item.value">
       </el-option>
     </el-select>
   </div>
   <div>
     <el-table
         :data="tableData"
         border
         class="rz-table"
         :header-cell-class-name="headerCellClassName"
         :header-row-class-name="headerRowClassName"
         style="width: 100%">

       <el-table-column label="序号">
         <template slot-scope="scope">
           <span>{{scope.$index}}</span>
         </template>
       </el-table-column>
       <el-table-column
           prop="date"
           label="日期"
           width="120">
       </el-table-column>
       <el-table-column
           prop="name"
           label="姓名"
           width="180">
       </el-table-column>
       <el-table-column
           prop="address"
           label="地址" >
       </el-table-column>
       <el-table-column
           prop="checkboxs"
           label="复选框" >
         <template slot-scope="{row}">
           <el-checkbox v-model="item.value" @change="changeSubGrop(row,_index)" v-for="(item,_index) in row.checkboxs">{{item.label}} </el-checkbox>
         </template>
       </el-table-column>
       <el-table-column
           label="操作" fixed="right">
         <template slot-scope="scope">
           <el-button @click="edit(scope.row.id,scope.$index)">编辑</el-button>
         </template>
       </el-table-column>
     </el-table>
     <el-button></el-button>
   </div>

   <el-upload
       class="upload-demo custom-upload"
       action="https://jsonplaceholder.typicode.com/posts/"
       :on-preview="handlePreview"
       :on-remove="handleRemove"
       :before-remove="beforeRemove"
       multiple
       :limit="3"
       :on-exceed="handleExceed"
       :file-list="fileList">
     <el-button size="small" type="primary">点击上传</el-button>
     <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
   </el-upload>

   <el-button type="primary" @click="testBtn"> 测试 </el-button>

   <el-button type="primary" @click="getDifVals"> 数组中不同的值拿出来 </el-button>

 </div>
</template>

<script>
import comTest from "./comTest";
export default {
  components:{
    comTest
  },
  watch:{
    changeValue:{
      handler(newV,oldV){
        console.log("newV:",newV())
      },
      immediate:true,
      deep:true
    }
  },
  data() {
    return {
      comValue:1,
      fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
     options: [{
          id:1,
          value: '选项1',
          label: '黄金糕'
        }, {
          id:2,
          value: '选项2',
          label: '双皮奶'
        }, {
          id:3,
          value: '选项3',
          label: '蚵仔煎'
        }, {
         id:4,
          value: '选项4',
          label: '龙须面'
        }, {
           id:5,
          value: '选项5',
          label: '北京烤鸭'
        }],
      value: '',
      value2:'',
      tableData: [{
        id:'1',
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄',
        checkboxs:[
          {
            label:'测试1',
            value:true
          },
          {
            label:'测试2',
            value:false
          }
        ]
      }, {
        id:'2',
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄',
        checkboxs:[
          {
            label:'测试1',
            value:false
          },
          {
            label:'测试2',
            value:false
          }
        ]
      }, {
        id:'3',
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄',
        checkboxs:[
          {
            label:'测试1',
            value:false
          },
          {
            label:'测试2',
            value:true
          }
        ]
      }, {
        id:'4',
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄',
        checkboxs:[
          {
            label:'测试1',
            value:1
          },
          {
            label:'测试2',
            value:1
          }
        ]
      }]
    }
  },

  methods:{
    testBtn(){
      let arr = [{num:9}, {num:' 10 '}, {num:11}]
      let vals = arr.map((item)=>{return { aa:item.num,bb:'***'}})
      console.log("vals:",vals)

      let str = '  10 '
      console.log("--**--:",Number(str))
      console.log("----:",Number(str) > 9)
    },
    changeValue(val){
      console.log("----val",val)
    },
    compare(){
      this.B = [{id:1},{ id:2}] ;
      let optionsJson = this.options.map(item=>{
         this.B.map(_item=>{
           console.log("item.id == _item.id:",item.id == _item.id)
           if (item.id == _item.id){
             item.disabled = true ;
           }else{
             item.disabled = false ;
           }
         })

        return item ;
      })

      console.log("optionsJson:",optionsJson)


      this.options = optionsJson ;
    },
    edit(id,index){
      console.log("id:",id,"index:",index)
    },
    headerRowClassName(){
      return 'header-row-bg'
    },
    headerCellClassName(){

    },
    changeSubGrop(row,index) {
      //所有选项全未勾选，则flag返回true
      let flag = row.checkboxs.every(item => {
        return !item.check
      })

      //flag为true，表示所有的项都未选勾选，所以最后一次操作的项复原回勾选状态
      if (flag) {
        row.checkboxs[index].check = true;
        this.$message.error('至少要勾选一项')
        return;
      }
    },
    changeMulSelect(){
      console.log("value2:",this.value2)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    getDifVals(){
      const targetArr  = [
        {id:"111",name:'xiaoxiao',num:4,total:66},
        {id:"111",name:'xiaohogn',num:5,total:66},
        {id:"22",name:'xiaoming',num:'89 ',total:22},
        {id:"33",name:'xiaoxue',num:7,total:44},
        {id:"33",name:'xiaoxue1',num:8,total:13},
      ]

      let flag = this.checkPass(targetArr,'id','num','total')
      console.log("---------flag:",flag)


    },
    /**
     *
     * @param targetArr 目标集合
     * @param difProp   可以用来区分不同EPR项目的属性，如项目id，项目name....
     * @param sumColProp 求和列的属性
     * @param compareProp 比较值的属性，也就是最终要与求和结果做比较的那个属性，如合同总金额
     * @returns {this is *[]}
     */
    checkPass(targetArr,difProp,sumColProp,compareProp){
      if (targetArr.length == 0) return true ;
      const groupedObjects = this.groupById(targetArr, difProp);//将相同ERP的对象放到一个数组中（即分堆）,构建数据结构，如 {10:[{},{}....],20:[{},{}...],30:[{},{}...]},EPR项目名作为key
      console.log(groupedObjects);
      let groupCheckResult = [] ; //将每个ERP集合的验证结果存到一个数组中，构建数据结构，如[false,true,false.....],项目为10的验证结果是false，项目为20的验证结果是true，项目为30的验证结果是false....
      for (let key in groupedObjects) { //对分堆后的数据遍历，{10:[{},{}....],20:[{},{}...],30:[{},{}...]},
        console.log("key:", key)
        let values = this.pluckArray(groupedObjects[key],sumColProp);//将相同ERP的sumColProp属性值放到数组中，构建数据结构，如[3,5,6...]
        console.log("values:",values)
        let sum = values.reduce((cur, next) => {//对相同ERP所有对象中的sumColProp属性值（整一列）相加求和
          return Number(cur) + Number(next);
        }, 0);
        if (sum > groupedObjects[key][0][compareProp]){//判断求和后是否大于该ERP的compareProp,如果大于则不符合要求
          console.log(groupedObjects[key][0]['name']+"的和不等大于total值")
          groupCheckResult.push(false)
        }else{
          groupCheckResult.push(true)
        }
        console.log("sum:", sum, groupedObjects[key][0].total)
      }
      console.log("groupCheckResult:",groupCheckResult)
      let validateResult = groupCheckResult.every(item =>  item) //[false,true,false.....]结果集只要有一个不符合要求,就返回false。
      return validateResult ;
    },
     //返回 求和的目标列单元格的所有值，如[3,5,6...]
     pluckArray(arr, propName) {
        return arr.map(function(item) {
          return item[propName];
        });
      },
     //分堆 如 {10:[{},{}....],20:[{},{}...],30:[{},{}...]},对象中的key（10,20,30...）为EPR项目名
     groupById(arr, idKey) {
      return arr.reduce((acc, obj) => {
        const id = obj[idKey];
        if (!acc[id]) acc[id] = [];
            acc[id].push(obj);
            return acc;
          }, {});
      },
     deepClone(oldData) {
        if (typeof oldData === "object" && oldData !== null) {
          let res = Array.isArray(oldData) ? [] : {};
          for (let k in oldData) {
            if (oldData.hasOwnProperty(k)) {
              res[k] = this.deepClone(oldData[k])
            }
          }
          return res
        } else {
          return oldData
        }
      }
    }
}
</script>
<style >
/*.header-row-bg{background-color:#f5f7fa!important;}*/
/*.rz-table-header{*/
/*  padding: 2px 0;*/
/*  font-weight: normal;*/
/*  font-size: 12px;*/
/*}*/
.rz-table.el-table{
   .header-row-bg{
      th{
         padding:0 ;
        .cell{
          font-size: 12px;
          font-weight: normal;
          background-color: #f5f7fa;
        }
      }
   }
}

 .custom-upload .el-upload-list {
   display: none !important;
 }
</style>